public class BinarySearch {

    // 二分查找的递归实现
    public static int binarySearch(int[] arr, int target) {
        return binarySearch(arr, target, 0, arr.length - 1);
    }

    private static int binarySearch(int[] arr, int target, int left, int right) {
        if (left > right) {
            return -1; // 没有找到目标元素
        }

        int mid = left + (right - left) / 2;

        if (arr[mid] == target) {
            return mid;
        } else if (arr[mid] > target) {
            return binarySearch(arr, target, left, mid - 1);
        } else {
            return binarySearch(arr, target, mid + 1, right);
        }
    }

    // 二分查找的非递归实现
    public static int binarySearchIterative(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2;

            if (arr[mid] == target) {
                return mid;
            } else if (arr[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }

        return -1; // 没有找到目标元素
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int target = 5;

        // 使用递归方法进行二分查找
        int result = binarySearch(arr, target);
        if (result != -1) {
            System.out.println("元素 " + target + " 在数组中的索引是: " + result);
        } else {
            System.out.println("元素 " + target + " 不在数组中");
        }

        // 使用非递归方法进行二分查找
        result = binarySearchIterative(arr, target);
        if (result != -1) {
            System.out.println("元素 " + target + " 在数组中的索引是: " + result);
        } else {
            System.out.println("元素 " + target + " 不在数组中");
        }
    }
}
